package mill

import (
	"context"
	"github.com/ThreeDotsLabs/watermill"
	"github.com/ThreeDotsLabs/watermill/message"
	"github.com/ThreeDotsLabs/watermill/pubsub/gochannel"
	"proxy_resource_test/services/mill/task"
	"proxy_resource_test/utils/logging"
)

var (
	logger = watermill.NewStdLogger(false, false)
	PubSub = gochannel.NewGoChannel(gochannel.Config{
		OutputChannelBuffer: 10000,
	}, logger)
)

const (
	IpInfoRegion = "ip_info_region" // ip识别信息 数据入库
)

func SetUpWater() error {
	router, err := message.NewRouter(message.RouterConfig{}, logger)
	if err != nil {
		panic(err)
	}

	for topic, cfg := range task.TopicConfigs {
		// 为每个 topic 创建独立 BatchProcessor
		bp := task.NewBatchProcessor(cfg)

		t := topic
		_ = router.AddNoPublisherHandler(
			"handler_"+t,
			t,
			PubSub,
			func(msg *message.Message) error {
				msg.Metadata.Set("topic", t)
				return bp.AcceptConsumeTask(msg)
			},
		)
	}

	ctx := context.Background()
	if err := router.Run(ctx); err != nil {
		logging.Error("step -watermill err :", err.Error())
		return nil
	}
	return nil
}
